package gautobgchanger;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 * This Class is for opening a trayicon, in the system tray
 * @author b1o
 */
public class SystemTrayIcon
{

    private String interval;

    /**
     * Creates a system tray icon that can be accessed so that you can change
     * the interval and path on the fly
     */
    public void createSystemTray()
    {
        final TrayIcon trayIcon;
        //checks if SystemTray is supported on current platform
        if (SystemTray.isSupported())
        {
            //gets the system tray of the desktop manager
            SystemTray tray = SystemTray.getSystemTray();
            //Image of the trayicon
            Image image = Toolkit.getDefaultToolkit().getImage("icon.gif");
            //creates a mouselistener
            MouseListener mouseListener = new MouseListener()
            {
                /**
                 * All these are for testing
                 */
                public void mouseClicked(MouseEvent e)
                {
                    System.out.println("Tray Icon - Mouse clicked!");
                }

                public void mouseEntered(MouseEvent e)
                {
                    System.out.println("Tray Icon - Mouse entered!");
                }

                public void mouseExited(MouseEvent e)
                {
                    System.out.println("Tray Icon - Mouse exited!");
                }

                public void mousePressed(MouseEvent e)
                {
                    System.out.println("Tray Icon - Mouse pressed!");
                }

                public void mouseReleased(MouseEvent e)
                {
                    System.out.println("Tray Icon - Mouse released!");
                }
            };
            //an event that exits the program
            ActionListener exitListener = new ActionListener()
            {

                public void actionPerformed(ActionEvent e)
                {
                    System.out.println("Exiting...");
                    System.exit(0);
                }
            };

            //opens up a dialog that you can set the interval in
            ActionListener setIntervalListener = new ActionListener()
            {

                public void actionPerformed(ActionEvent e)
                {
                    String interval = JOptionPane.showInputDialog("Set the interval for each cycle (in seconds)");
                    ConfWriter cw = new ConfWriter();
                    //if for some reason the dumb user manages to write anything but a number, do nothing
                    if (isNumber(interval))
                    {
                        try
                        {
                            cw.SetInterval(interval);
                            System.out.println("Setting interval to " + interval);
                        } catch (Exception ex)
                        {
                        }
                    }

                }
            };
            //opens up a folder chooser to change the path of the wallpapers
            ActionListener setPathListener = new ActionListener()
            {

                public void actionPerformed(ActionEvent e)
                {
                    ShowFileChooser(true);
//                    JFileChooser fileopen = new JFileChooser();
//                    fileopen.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//
//                    int ret = fileopen.showDialog(null, "Open file");
//
//                    if (ret == JFileChooser.APPROVE_OPTION)
//                    {
//                        File file = fileopen.getSelectedFile();
//                        String path = file.getPath();
//                        try
//                        {
//                            System.out.println("Setting Path to " + path);
//                            new ConfWriter().SetPath(path);
//                        } catch (Exception ex)
//                        {
//                            System.err.println(ex.getMessage());
//                        }
//                    }
                }
            };

            //Creates a new AWT popup menu
            PopupMenu popup = new PopupMenu();

            //Creates a menu item
            MenuItem defaultItem = new MenuItem("Set Interval");
            //add an actionlistener to the menu item
            defaultItem.addActionListener(setIntervalListener);
            //add the menuitem to the popup menu
            popup.add(defaultItem);
            defaultItem = new MenuItem("Set Path");

            defaultItem.addActionListener(setPathListener);

            popup.add(defaultItem);

            defaultItem = new MenuItem("Exit");

            defaultItem.addActionListener(exitListener);

            popup.add(defaultItem);
            trayIcon = new TrayIcon(image, "Background Changer", popup);
            ActionListener actionListener = new ActionListener()
            {

                public void actionPerformed(ActionEvent e)
                {
                    trayIcon.displayMessage("Action Event",
                            "An Action Event Has Been Performed!",
                            TrayIcon.MessageType.INFO);
                }
            };

            //autosizes the image
            trayIcon.setImageAutoSize(true);
            //add an actionlistener and a mouse listener to the trayicon
            trayIcon.addActionListener(actionListener);
            trayIcon.addMouseListener(mouseListener);
            try
            {
                //adds the trayicon to the systemtray
                tray.add(trayIcon);
            } catch (AWTException e)
            {
                System.out.println("TrayIcon could not be added.");
            }
        } else
        {
            System.out.println("Your DesktopManager isn't supported");
        }

    }
/**
 * Checks if a string is a number
 * @param str
 * @return
 */
    private boolean isNumber(String str)
    {
        //It can't contain only numbers if it's null or empty...
        if (str == null || str.length() == 0)
        {
            return false;
        }

        for (int i = 0; i < str.length(); i++)
        {

            //If we find a non-digit character we return false.
            if (!Character.isDigit(str.charAt(i)))
            {
                return false;
            }
        }

        return true;
    }

    /**
     * Shows a FileChooser to set the folder for the wallpapers
     * @param oldConfig Set false if you want to make a new config
     */
    public void ShowFileChooser(boolean oldConfigExcists)
    {
        JFileChooser fileopen = new JFileChooser();
        fileopen.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        int ret = fileopen.showDialog(null, "Open file");

        if (ret == JFileChooser.APPROVE_OPTION)
        {
            File file = fileopen.getSelectedFile();
            String path = file.getPath();
            try
            {
                System.out.println("Setting Path to " + path);
                if (!oldConfigExcists)
                {
                    new ConfWriter().setBasicConfig(path);
                } else
                {
                    new ConfWriter().SetPath(path);
                }
            } catch (Exception ex)
            {
                System.err.println(ex.getMessage());
            }
        }
    }
}
